
import _ from 'lodash'
import { getTenantConfigCommand, postTenantConfigCommand } from '@/api/tenant'
import { generateId } from '@/utils'
import Vue from 'vue'
import { CONFIG_DATA, DEFAULT_EVENT_SOURCES } from '@/views/tenant/constant'
const state = {

    configData: {}
}
const getters = {
    getCommandList: state => {
        return function (mqttType) {
            const filterData = state.configData.children.find(f => f.name == state.configData._activeName)
            return filterData.children.filter(item => item.name == state.configData._summary)
        }

    },
}
const mutations = {
    setOpen: (state, data) => {
        let filterData = state.configData.children.find(f => f.name == state.configData._activeName)
        filterData = filterData.children.filter(item => item.name == state.configData._summary)
        filterData.forEach(item => {
            if (item.name == data.name) {
                item.isopen = !item.isopen
            }
        })
    },
    delConfig: (state, id) => {
        state.configData.children.forEach(item => {
            if (item.name == state.configData._activeName) {
                item.children.forEach((ele, index) => {
                    if (ele.id == id) {
                        item.children.splice(index, 1)
                    }
                })
            }
        })
    },
    addCommand: (state, id) => {
        state.configData.children.forEach(item => {
            if (item.name == state.configData._activeName) {
                item.children.push({
                    attributes: _.cloneDeep(state.configData._formItem).map(item => {
                        // 添加的时候给指定的字段赋默认值
                        if (item.name == 'clientId') {
                            item.value = `sl_mqtt_${generateId(8)}`
                        }
                        if (item.name == 'topic') {
                            item.value = ''
                            item.summary = '$avic/superlink/iot/${tenant.token}/+/'
                        }
                        if (item.name == 'numThreads') {
                            item.value = 5
                        }
                        return item
                    }),
                    id: generateId(),
                    name: state.configData._summary
                })
            }
        })
    },
    editCommand: (state, row) => {
        state.configData.children.forEach(item => {
            if (item.name == state.configData._activeName) {
                item.children.forEach((ele, index) => {
                    if (ele.id == row.id) {
                        // 使用set触发页面更新
                        Vue.set(item.children, index, _.cloneDeep(row))
                    }
                })
            }
        })

    },
    setConfigData: (state, data) => {
        state.configData = data
    },
}

const actions = {
    submit({ commit, state }, configToken) {
        return new Promise((resolve, reject) => {
            postTenantConfigCommand(useSubmitData(state.configData), configToken, state.configData._activeName).then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })

    },
    getTenantConfigCommand({ state, commit }, configData) {
        return new Promise(async (resolve, reject) => {
            const { data } = await getTenantConfigCommand(configData);
            const { activeName } = configData
            const { summary, idKey, formItem, defaultKey } = CONFIG_DATA.find(item => item.name == activeName)
            const filterData = data.children.find(f => f.name == activeName)
            if (filterData) {
                const newData = filterData.children.filter(item => item.name == summary)
                // FORM_ITEM完整的表单字段
                newData.map(item => {
                    const CLONE_FORM_ITEM = _.cloneDeep(formItem)
                    CLONE_FORM_ITEM.forEach(form => {
                        const destinationIdIsDefalut = item.attributes.find(f => f.name == idKey)?.value
                        const disabled = defaultKey.includes(destinationIdIsDefalut)
                        Vue.set(item, 'disabled', disabled)
                        item.attributes.forEach(attr => {
                            if (form.name == attr.name) {
                                Vue.set(form, 'value', attr.value)
                                if (attr.name == 'cleanSession') {
                                    Vue.set(form, 'value', form.value === 'true' ? true : false)
                                }
                                if (attr.name == 'topic' && attr.value) {
                                    const topicVal = attr.value.split('/+/')
                                    Vue.set(form, 'value', topicVal[1])
                                    Vue.set(form, 'summary', topicVal[0] + '/+/')
                                }
                            }

                            // else if (attr.name == 'port') {
                            //     Vue.set(attr, 'value', attr.value + '')
                            // }

                        })
                    })
                    item.attributes = CLONE_FORM_ITEM
                    Vue.set(item, 'attributes', CLONE_FORM_ITEM)
                    item.isopen = false

                })
                commit('setConfigData', { ...data, _defaultKey: defaultKey, _activeName: activeName, _summary: summary, _idKey: idKey, _formItem: _.cloneDeep(formItem) })
                resolve(data)
            }
        });
    },

}
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}

// 删除数组总value为空的对象
const useSubmitData = (data) => {
    const cloneData = _.cloneDeep(data)
    const filterData = cloneData.children.find(f => f.name == cloneData._activeName)
    const newData = filterData.children.filter(item => item.name == cloneData._summary)
    newData.map(item => {
        item.attributes = item.attributes.map(m => {
            // if (m.name == 'hostname' && m.value == 'localhost') {
            //     m.value = '${localhost}'
            // }
            // 只传递必要的数据
            if (m.name == 'topic') {
                m.value = `${m.summary}${m.value}`
            }
            return {
                name: m.name,
                value: m.value
            }
        })
        _.remove(item.attributes, function (x) {
            return !x.value
        })
        delete item.isopen
        delete item.disabled
        // 只传递必要的数据

    })
    return cloneData
}
